package services

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"regexp"
	"strings"
	"time"
)


/* func JenkinsAdd(caseServerity string, project string, runningEnv string, mailReceiver string) string {
	
	url :=  "http://10.100.0.178:5099/job/test_team/job/test/job/testcase-pytest-pipeline-customer/buildWithParameters"
	
	body :=fmt.Sprintf(` {"parameter":[{"name":"caseServerity","value":%s},
	{"name":"project","value":%s},
	{"name":"runningEnv","value":%s},
	{"name":"gitBranch","value":"develop"},
	{"name":"mailReceiver","value":%s}]}`,caseServerity,project,runningEnv,mailReceiver)

	client := &http.Client{}//客户端,被Get,Head以及Post使用
    reqest, err := http.NewRequest("POST", url, strings.NewReader(body))
	if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
	reqest.Header.Set("Content-Type", "multipart/form-data") 
	reqest.Header.Set("Authorization", "Basic dGVzdF90ZWFtOnRlc3RAMjAyMSE=") 
	resp, err := client.Do(reqest)//发送请求
	if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
    defer resp.Body.Close()//一定要关闭resp.Body
    content, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
	locationinfo := resp.Header
	reg := regexp.MustCompile(`item/(.+?)/`)
	locations := reg.FindStringSubmatch(locationinfo["Location"][0])
	queueid := locations[1]
    fmt.Println(string(content))
	return queueid
} */


func JenkinsAdd(planid string, caseServerity string, project string, runningEnv string, module string, mailReceiver string) string {	
	urlj :=  "http://10.100.0.178:5099/job/test_team/job/test/job/testcase-pytest-pipeline-customer/buildWithParameters"
	form := url.Values{}
	form.Set("taskId", planid)
	form.Set("caseServerity", caseServerity)	
	form.Set("project", project)
	form.Set("runningEnv", runningEnv)
	form.Set("microService", module)
	form.Set("mailReceiver", mailReceiver)
	client := &http.Client{}//客户端,被Get,Head以及Post使用
    reqest, err := http.NewRequest("POST", urlj, strings.NewReader(form.Encode()))
	if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
	reqest.Header.Set("Content-Type", "application/x-www-form-urlencoded") 
	reqest.Header.Set("Authorization", "Basic dGVzdF90ZWFtOnRlc3RAMjAyMSE=") 
	resp, err := client.Do(reqest)//发送请求
	if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
    defer resp.Body.Close()//一定要关闭resp.Body
    content, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
	locationinfo := resp.Header
	reg := regexp.MustCompile(`item/(.+?)/`)
	locations := reg.FindStringSubmatch(locationinfo["Location"][0])
	queueid := locations[1]
    fmt.Println(string(content))
	return queueid
}

func JenkinsAddbyname(projectname string) string {	
	urlj :=  "http://10.100.0.178:5099/job/test_team/job/test/job/"+ projectname + "/build"
	fmt.Println("开始触发流水线", urlj)
	client := &http.Client{}//客户端,被Get,Head以及Post使用
    reqest, err := http.NewRequest("POST", urlj, strings.NewReader(""))
	if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
	reqest.Header.Set("Content-Type", "application/x-www-form-urlencoded") 
	reqest.Header.Set("Authorization", "Basic dGVzdF90ZWFtOnRlc3RAMjAyMSE=") 
	resp, err := client.Do(reqest)//发送请求
	if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
    defer resp.Body.Close()//一定要关闭resp.Body
    content, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
	locationinfo := resp.Header
	reg := regexp.MustCompile(`item/(.+?)/`)
	locations := reg.FindStringSubmatch(locationinfo["Location"][0])
	queueid := locations[1]
    fmt.Println(string(content))
	return queueid
}

func Jenkinsgetnumber(queueid string) (string, float64){
	url :=  "http://10.100.0.178:5099/queue/item/" + queueid + "/api/json"
	client := &http.Client{}//客户端,被Get,Head以及Post使用
    reqest, err := http.NewRequest("GET", url, nil)
	if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
	reqest.Header.Set("Authorization", "Basic dGVzdF90ZWFtOnRlc3RAMjAyMSE=") 
	var responscon = ""
	keyw := "number"
	reporturl := ""
	var reportnumber float64
	var mmresult map[string]interface{}
	for {
		if !strings.Contains(responscon, keyw) {		
			resp, err := client.Do(reqest)//发送请求
			if err != nil {
				fmt.Println("Fatal error ", err.Error())
			}
			defer resp.Body.Close()//一定要关闭resp.Body
			content, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				fmt.Println("Fatal error ", err.Error())
			}
			//fmt.Println(string(content))			
			responscon = string(content)
			json.Unmarshal(content, &mmresult)	
			time.Sleep(1 * time.Second)		
	} else {
		reporturl = mmresult["executable"].(map[string]interface{})["url"].(string)	
		reportnumber = mmresult["executable"].(map[string]interface{})["number"].(float64)

		//fmt.Println("ppppp:",reporturl)
		break
	}	
}
	return reporturl, reportnumber
}


func JenkinsJobStatus(reportnumber float64) float64 {
	urlj :=  "http://10.100.0.178:5099/job/test_team/job/test/job/testcase-pytest-pipeline-customer/api/json"
	client := &http.Client{}//客户端,被Get,Head以及Post使用
    reqest, err := http.NewRequest("GET", urlj, nil)
	if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
	reqest.Header.Set("Content-Type", "application/x-www-form-urlencoded") 
	reqest.Header.Set("Authorization", "Basic dGVzdF90ZWFtOnRlc3RAMjAyMSE=") 
	resp, err := client.Do(reqest)//发送请求
	if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
    defer resp.Body.Close()//一定要关闭resp.Body
    content, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
	var tmpresult map[string]interface{}	
	json.Unmarshal(content, &tmpresult)
	//fmt.Println("pppppppp:",string(content))	
	lastStableBuild :=  tmpresult["lastCompletedBuild"].(map[string]interface{})["number"].(float64)
	//fmt.Println("测试number:",lastStableBuild)
	return lastStableBuild
	
}


func JenkinsJobStatusbyName(reportnumber float64, projectname string) float64 {
	urlj :=  "http://10.100.0.178:5099/job/test_team/job/test/job/" + projectname + "/api/json"
	client := &http.Client{}//客户端,被Get,Head以及Post使用
    reqest, err := http.NewRequest("GET", urlj, nil)
	if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
	reqest.Header.Set("Content-Type", "application/x-www-form-urlencoded") 
	reqest.Header.Set("Authorization", "Basic dGVzdF90ZWFtOnRlc3RAMjAyMSE=") 
	resp, err := client.Do(reqest)//发送请求
	if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
    defer resp.Body.Close()//一定要关闭resp.Body
    content, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
    }
	var tmpresult map[string]interface{}	
	json.Unmarshal(content, &tmpresult)
	//fmt.Println("pppppppp:",string(content))	
	lastStableBuild :=  tmpresult["lastCompletedBuild"].(map[string]interface{})["number"].(float64)
	//fmt.Println("测试number:",lastStableBuild)
	return lastStableBuild
	
}